<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Exception\Handler;

use App\Constants\Constants;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;

use Psr\Http\Message\ResponseInterface;

use Throwable;

/**
 * 验证器异常接管
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Model
 */
class ValidationExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $error = $throwable->validator->errors()->first();

        $data = json_encode([
            'code' => 403,
            'message' => str_replace('validation.', '', __('validation.' . $error)),
            'data' => []
        ], JSON_UNESCAPED_UNICODE);

        $this->stopPropagation();

        return $response->withStatus(200)
            ->withBody(new SwooleStream($data))
            ->withHeader('Content-Type', 'application/json;charset=utf-8')
            ->withAddedHeader('Server', Constants::COPYRIGHT);
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}
